<?php


namespace App\Resource\Service;


use App\Common\Constants\ErrorCode;
use App\Common\Service\BaseService;
use App\Resource\Event\UpdateGoodsCache;
use App\Resource\Model\CrdNavigationModel;
use App\Resource\Model\CrdNavigationShopModel;
use App\Resource\Model\GoodsModel;
use App\Resource\Model\NavigationModel;
use App\Resource\Model\NavigationShopModel;
use App\Resource\Model\ShopGroupModel;
use App\Resource\Model\ShopModel;
use Exception;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Psr\EventDispatcher\EventDispatcherInterface;

class ResourceService extends BaseService
{
    /**
     * @param string $category
     * @param int $id
     * @param string $goodsId
     *
     * @return array
     */
    public function bindGoods(string $category, int $id, string $goodsId, $shopType = null)
    {
        $arr = [];
        switch ($category) {
            case 'navigation':
                $goodsIdArr = explode(',', $goodsId);
                if($shopType){
                    //次日达
                    $exist = CrdNavigationModel::where(['id' => $id])->exists();
                }else{
                    //普通商城
                    $exist = NavigationModel::where(['id' => $id])->exists();
                }

                if (!$exist) {
                    return ['code' => ErrorCode::NOT_EXIST];
                }
                if($shopType){
                    $db = Db::table('hf_crd_navigation_goods');
                }else{
                    $db = Db::table('hf_navigation_goods');
                }

                $keys = 'navigation_id';
                foreach ($goodsIdArr as $key => $val) {
                    $arr[$key][$keys] = $id;
                    $arr[$key]['goods_id'] = $val;
                }
                break;
            default:
        }
        try {
            DB::transaction(function () use ($db, $keys, $arr, $id) {
                $db->where([$keys => $id])->delete();
                $db->insert($arr);
            });
        } catch (Exception $e) {
            return ['code' => ErrorCode::NOT_IN_FORCE];
        }

        return ['code' => ErrorCode::SUCCESS, 'data' => []];
    }

    /**
     * @param int $goodsId
     * @param string $shopIds
     * @param int $shopType 商品类别：0为及时达，1为次日达
     *
     * @return array
     */
    public function unBindGoods(int $goodsId, string $shopIds, int $shopType = 0)
    {
        $goods = GoodsModel::where(['id' => $goodsId])->first();
        if($shopType == 1){
            // 次日达商品下架
            $goods->crd_shop_ids = $shopIds;
            $res = $goods->save();
            if (!$res) {
                return ['code' => ErrorCode::NOT_IN_FORCE];
            }
        }else{
            $goods->shop_ids = $shopIds;
            $res = $goods->save();
            if (!$res) {
                return ['code' => ErrorCode::NOT_IN_FORCE];
            }
            $shops = explode(",", $shopIds);
            $this->redis->del("Goods-Put:" . $goodsId);
            foreach ($shops as $shopId) {
                $this->redis->sAdd("Goods-Put:" . $goodsId, $shopId);
            }
        }
        $this->eventDispatcher->dispatch(new UpdateGoodsCache('shop_sale', $goodsId, $goods));
        return ['code' => ErrorCode::SUCCESS, 'data' => [], 'info' => ['target_id' => $goodsId, 'remarks' => 'shop_ids:'.$shopIds]];
    }

    /**
     * @param int $id
     * @param int $shopId
     * @param int $type
     * @param $unBindShop
     *
     * @return array
     */
    public function unBindShop(int $id, int $shopId, int $type, $shopType = null)
    {
        if($shopType){
            // 次日达商城
            $res = CrdNavigationShopModel::query()
                ->where(['navigation_id' => $id, 'shop_id' => $shopId, 'type' => $type])
                ->delete();
        }else{
            // 普通商城
            $res = NavigationShopModel::query()
                ->where(['navigation_id' => $id, 'shop_id' => $shopId, 'type' => $type])
                ->delete();
        }
        if (!$res) {
            return ['code' => ErrorCode::NOT_IN_FORCE];
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => $res];
    }

    /**
     * @param int $goodsId
     *
     * @return array
     */
    public function goodsUnbindShop(int $goodsId, int $shopType)
    {
        if($shopType == 1){
            $unbindShop = GoodsModel::query()->where(['id' => $goodsId])->value('crd_shop_ids');
        }else{
            $unbindShop = GoodsModel::query()->where(['id' => $goodsId])->value('shop_ids');
        }

        if ($unbindShop) {
            $unbindShopArr = explode(',', $unbindShop);
            $shopList = ShopModel::query()->whereIn('shop_id', $unbindShopArr)
                ->select(['shop_id', 'shop_name', 'shop_man', 'shop_tel', 'shop_group_id', 'shop_desc', 'address'])
                ->get();
            $shopGroupIds = array_unique(array_column($shopList->toArray(), 'shop_group_id'));
            $shopGroup = ShopGroupModel::query()->whereIn('id', $shopGroupIds)->pluck('shop_group_name', 'id')->toArray();
            foreach ($shopList as $k => $v) {
                $shopList[$k]['shop_group_name'] = $shopGroup[$v->shop_group_id];
            }
        } else {
            $shopList = [];
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => $shopList];
    }


    /**
     * @param string $category
     * @param int $id   首页导航等对象的 ID
     * @param string $shopId    店铺 ID
     * @param int $type
     *
     * @return array
     */
    public function bindShop(string $category, int $id, string $shopId, int $type, $shopType = null)
    {
        switch ($category) {
            case 'navigation':
                if($shopType){
                    // 次日达商城
                    $exist = CrdNavigationModel::where(['id' => $id])->exists();
                    if (!$exist) {
                        return ['code' => ErrorCode::NOT_EXIST];
                    }
                    $db = Db::table('hf_crd_navigation_shop');
                }else{
                    // 普通商城
                    $exist = NavigationModel::where(['id' => $id])->exists();
                    if (!$exist) {
                        return ['code' => ErrorCode::NOT_EXIST];
                    }
                    $db = Db::table('hf_navigation_shop');
                }

                $keys = 'navigation_id';
                break;
        }
        $shopIdArr = explode(',', $shopId);
        $arr = [];
        foreach ($shopIdArr as $key => $val) {
            $arr[$key][$keys] = $id;
            $arr[$key]['shop_id'] = $val;
            $arr[$key]['type'] = $type;
        }
        try {
            DB::transaction(function () use ($db, $keys, $arr, $id, $type) {
                $db->where([$keys => $id, 'type' => $type])->delete();
                $db->insert($arr);
            });
        } catch (Exception $e) {
            return ['code' => ErrorCode::NOT_IN_FORCE];
        }
        return ['code' => ErrorCode::SUCCESS, 'data' => []];
    }

}
